//
//  ChangeDNSViewController.m
//  PPScaleDemo
//
//  Created by 彭思远 on 2021/3/29.
//

#import "ChangeDNSViewController.h"
#import <PPScaleSDK/PPScaleFormatTool.h>
#define BLE_SEND_MAX_LEN 20
@interface ChangeDNSViewController ()<PPBleStateInterface>
@property (weak, nonatomic) IBOutlet UITextField *DNSTF;
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;
@property (nonatomic, strong) PPScaleManager *scaleManager;
@property (nonatomic, assign) PPBleWorkState state;

@end

@implementation ChangeDNSViewController

+ (instancetype)instance{
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ChangeDNSViewController"];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self connectScale];
}



- (void)connectScale{
    NSArray *deviceArr = [DeviceModel allObjects];
    NSMutableArray *macArr = @[].mutableCopy;
    for (DeviceModel *device in deviceArr) {
        [macArr addObject:device.deviceMac];
    }
    self.scaleManager = [[PPScaleManager alloc] initWithMacAddressList:macArr filterDeviceNameArr:nil andUserModel:nil];
    self.scaleManager.stateInterface = self;
    [self.scaleManager startSearching];
}

- (void)monitorBluetoothWorkState:(PPBleWorkState)state{
    self.state = state;
    if (state == PPBleWorkStateSearching) {
        self.title = @"扫描中";
    }else if (state == PPBleWorkStateSearchStop){
        self.title = @"停止扫描";
    }else if (state == PPBleWorkStateConnecting){
        self.title = @"设备连接中";
    }else if (state == PPBleWorkStateConnected){
        self.title = @"设备已连接";
    }else if (state == PPBleWorkStateDisconnected){
        self.title = @"设备已断开";
        [self.scaleManager reStartSearching];
    }
    self.changeBtn.enabled = state == PPBleWorkStateConnected ? YES:NO;
}


- (IBAction)changeBtnClick:(id)sender {
    // F800
    // F700
    Byte bytes1[2];
    bytes1[0] = 0xF8;
    bytes1[1] = 0x00;
    NSData *preData = [[NSData alloc] initWithBytes:bytes1 length:2];
    
    NSString *ipHEX =  [PPScaleFormatTool hexStringFromString:self.DNSTF.text ];
    NSData *ipData= [PPScaleFormatTool convertHexStrToData:ipHEX];
    NSInteger len = ipData.length;
    NSData *ipLen = [PPScaleFormatTool convertHexStrToData:[PPScaleFormatTool getHexByDecimal:len]];
    UInt8 bytes[len];
    memcpy(bytes, ipData.bytes, len);
    Byte crc=bytes[0];
    for (int i=1; i<len; i++) {
        crc = crc^bytes[i];
    }
    
    Byte crcbytes[1];
    crcbytes[0] = crc;
    NSData *crcData = [[NSData alloc] initWithBytes:crcbytes length:1];

    NSMutableData *msgData = [[NSMutableData alloc] init];
    [msgData appendData:preData];
    [msgData appendData:ipLen];
    [msgData appendData:crcData];
    [msgData appendData:ipData];
    
    NSMutableArray *commands = @[].mutableCopy;
    for (int i = 0; i < [msgData length]; i += BLE_SEND_MAX_LEN) {
        // 预加 最大包长度，如果依然小于总数据长度，可以取最大包数据大小
        if ((i + BLE_SEND_MAX_LEN) < [msgData length]) {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, BLE_SEND_MAX_LEN];
            NSData *subData = [msgData subdataWithRange:NSRangeFromString(rangeStr)];
            [commands addObject:subData];
 
        }
        else {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, (int)([msgData length] - i)];
            NSData *subData = [msgData subdataWithRange:NSRangeFromString(rangeStr)];
            [commands addObject:subData];
        }
    }
    
    [self writeCommands:commands];
}



- (void)writeCommands:(NSArray *)commands{
    if (self.state == PPBleWorkStateConnected) {
        [self.scaleManager writeDeveloperCommands:commands withReciveDataHandler:^(NSData *reciveData) {
            NSString *str = [PPScaleFormatTool data2String:reciveData];
            if ([str hasPrefix:@"f800"]) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Change Success" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [alertController dismissViewControllerAnimated:YES completion:nil];
                }];
                [alertController addAction:action];
                [self presentViewController:alertController animated:YES completion:nil];
            }
    
        }];
    }else{
    }
}


@end
